﻿using Pdf2epub.Interfaces;
using Pdf2epub.Model;

namespace Pdf2epub.BusinessLogic
{
    internal class ChapterDetection
    {
        private readonly Chapter[] m_ChapterHierarchy = new Chapter[7];

        private readonly IProjectContext m_ProjectContext;

        public ChapterDetection(IProjectContext projectContext)
        {
            m_ProjectContext = projectContext;
        }

        public void SetChaptersFromDetectedHeaders()
        {
            m_ProjectContext.FeedbackService.SetDetailText("Detecting chapters...");

            int chapterLevel = 0;
            ContentBlock previousBlock = null;
            foreach (ContentBlock block in m_ProjectContext.Content)
            {
                if ((block.HtmlTag >= HtmlReplacementTag.H1) && (block.HtmlTag <= HtmlReplacementTag.H6))
                {
                    chapterLevel = (int)block.HtmlTag;

                    if ((previousBlock != null) && (previousBlock.HtmlTag == block.HtmlTag) && (previousBlock.SourcePage == block.SourcePage))
                    {
                        m_ChapterHierarchy[chapterLevel].Headline = m_ChapterHierarchy[chapterLevel].Headline + block.Content;
                        block.Chapter = m_ChapterHierarchy[chapterLevel];
                    }
                    else
                    {
                        Chapter parentChapter = FindParentChapter(block);
                        Chapter chapter = new Chapter(parentChapter, block.Content);

                        m_ChapterHierarchy[chapterLevel] = chapter;

                        block.Chapter = chapter;
                    }
                }
                else if (block.HtmlTag >= HtmlReplacementTag.None)
                {
                    block.Chapter = m_ChapterHierarchy[chapterLevel];
                    if (block.Chapter == null)
                    {
                        block.Chapter = new Chapter(null, "unknown");
                    }
                }
                previousBlock = block;
            }
        }

        private Chapter FindParentChapter(ContentBlock block)
        {
            return m_ChapterHierarchy[(int)block.HtmlTag - 1];
        }
    }
}